// ==UserScript==
// @name         数据自动填充工具测试
// @namespace    http://tampermonkey.net/
// @version      1.8
// @description  从后端获取数据填充(SPA适配版)
// @author       e代农夫
// @match        https://admin.ednf.top/*
// @grant        GM_addStyle
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';
    
    // 检查当前URL是否为指定页面
    function isTargetPage() {
        return window.location.hash.includes('/bonsai-study/BonsaiVideoHost');
    }
    
    // 添加按钮样式
    GM_addStyle(`
        #autoFillBtn {
            position: fixed;
            top: 74px;
            right: 20px;
            z-index: 999999;
            padding: 8px 16px;
            background: #409EFF;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        #autoFillBtn:hover {
            background: #337ecc;
        }
        #autoFillBtn:disabled {
            background: #a0cfff;
            cursor: not-allowed;
        }
    `);
    
    // 创建自动填充按钮
    function createAutoFillButton() {
        if (!isTargetPage()) return;
        
        // 如果按钮已存在则不创建
        if (document.getElementById('autoFillBtn')) return;
        
        const button = document.createElement('button');
        button.id = 'autoFillBtn';
        button.textContent = '自动填充';
        document.body.appendChild(button);
        
        button.addEventListener('click', async function() {
            button.disabled = true;
            
            try {
                await fillTextarea();
            } catch (error) {
                console.error('填充失败:', error);
            } finally {
                button.disabled = false;
            }
        });
    }
    
    // 移除自动填充按钮
    function removeAutoFillButton() {
        const button = document.getElementById('autoFillBtn');
        if (button) {
            button.remove();
        }
    }
    
    // 监听路由变化
    function setupRouterListener() {
        // 监听hashchange事件
        window.addEventListener('hashchange', function () {
            if (isTargetPage()) {
                // 延迟执行以确保DOM已更新
                setTimeout(createAutoFillButton, 100);
            } else {
                removeAutoFillButton();
            }
        });
        
        // 监听可能的pushState/replaceState变化
        const originalPushState = history.pushState;
        const originalReplaceState = history.replaceState;
        
        history.pushState = function () {
            originalPushState.apply(this, arguments);
            window.dispatchEvent(new Event('locationchange'));
        };
        
        history.replaceState = function () {
            originalReplaceState.apply(this, arguments);
            window.dispatchEvent(new Event('locationchange'));
        };
        
        window.addEventListener('locationchange', function () {
            if (isTargetPage()) {
                setTimeout(createAutoFillButton, 100);
            } else {
                removeAutoFillButton();
            }
        });
    }
    
    // 页面加载完成后初始化
    window.addEventListener('load', function () {
        setupRouterListener();
        
        // 立即检查当前路由
        if (isTargetPage()) {
            // 延迟执行以确保DOM已加载
            setTimeout(createAutoFillButton, 1000);
        }
    });
    
    // 从后端获取数据
    async function fetchData() {
        try {
            // 生成设备指纹（与后端一致的逻辑）
            const generateFingerprint = async () => {
                const canvas = document.createElement('canvas');
                const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
                
                const features = {
                    userAgent: navigator.userAgent,
                    screenResolution: `${window.screen.width}x${window.screen.height}`,
                    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
                    webglVendor: gl?.getParameter(gl.VENDOR),
                    webglRenderer: gl?.getParameter(gl.RENDERER),
                    hardwareConcurrency: navigator.hardwareConcurrency || 'unknown'
                };
                
                const encoder = new TextEncoder();
                const data = encoder.encode(JSON.stringify(features));
                const hashBuffer = await crypto.subtle.digest('SHA-256', data);
                const hashArray = Array.from(new Uint8Array(hashBuffer));
                return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
            };
            
            const fingerprint = await generateFingerprint();
            
            // 使用与 AutoFillModule.vue 相同的 baseURL 格式
            const baseUrl = 'http://localhost:3000';
            
            const response = await fetch(`${baseUrl}/searchapi/searchdata/list?fingerprint=${fingerprint}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
            
            const result = await response.json();

            // 使用与 AutoFillModule.vue 相同的响应处理方式
            if (result.success) {
                if (result.data && result.data.length > 0) {
                    // 查找匹配设备指纹的数据
                    const matchingData = result.data.find(item => item.fingerprint === fingerprint);
                    if (matchingData) {
                        return matchingData;
                    } else {
                        throw new Error('未找到匹配的设备数据');
                    }
                } else {
                    throw new Error('后端未返回有效数据');
                }
            } else {
                throw new Error(result.message || '获取数据失败');
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            throw error;
        }
    }
    
    // 填充表单数据，确保返回布尔值
async function fillTextarea() {
    try {
        const data = await fetchData();
        
        // 获取所有文本域并按顺序填充
        const textareas = document.querySelectorAll('textarea.el-textarea__inner');
        let filledCount = 0;
        
        // 更新数据字段数组以匹配API返回的数据结构
        const dataFields = [
            'projectName',
            'constructionAddress',
            'constructionContent',
            'biddingForm',
            'biddingUnit',
            'winningBidder',
            'bidAmount',
            'constructionUnit',
            'constructionUnitLeader',
            'constructionSupervisor',
            'constructionEndPerson',
            'constructionEndOpinion',
            'totalPrice',
            'winningTime',
            'constructionPeriod',
            'projectStartDate',
            'completionDate'
        ];
        
        // 按顺序填充每个文本域
        textareas.forEach((textarea, index) => {
            if (index < dataFields.length && data[dataFields[index]]) {
                textarea.value = data[dataFields[index]];
                textarea.dispatchEvent(new Event('input', {bubbles: true}));
                textarea.dispatchEvent(new Event('change', {bubbles: true}));
                filledCount++;
            }
        });
        
        return filledCount > 0;
    } catch (error) {
        console.error('填充表单失败:', error);
        throw error;
    }
}


})();
